import { useStore } from 'vuex'
import { computed } from 'vue'
import { save, remove } from '../../assets/js/array-store'
import { FAVORITE_KEY } from '../../assets/js/constant'

export default function useFavoriteEffect () {
  const store = useStore()
  const favoriteList = computed(() => store.state.favoriteList)
  const maxLen = 100

  // icon状态
  const getFavoriteIcon = (song) => {
    return isFavorite(song) ? 'icon-favorite' : 'icon-not-favorite'
  }
  // 喜欢和不喜欢切换
  const toggleFavorite = (song) => {
    const list = isFavorite(song) ? remove(FAVORITE_KEY, compare)
      : save(song, FAVORITE_KEY, compare, maxLen)

    store.commit('setFavoriteList', list)
    function compare (item) {
      return item.id === song.id
    }
  }
  function isFavorite (song) {
    return ~favoriteList.value.findIndex(item => item.id === song.id)
  }
  return { getFavoriteIcon, toggleFavorite }
}
